#include "mysql.h"
#include "connpool.hpp"

mysql::mysql()
    : m_mysql_conn(NULL)
{
    printf("mysql 类构造\n");
    m_mysql_conn = mysql_conn_pool::get()->get_connect();
}

mysql::~mysql()
{
    printf("mysql 类析构\n");
    mysql_conn_pool::get()->disconnect(m_mysql_conn);
}

bool mysql::execut(const char *sql)
{
    if (mysql_query(m_mysql_conn, sql))
    {
        return true;
    }
    else
    {
        return false;
    }
    return false;
}

const char *mysql::error()
{
    return mysql_error(m_mysql_conn);
}

////////对外Lua暴露函数//////////////////////////
int newMysql(lua_State *L)
{
    mysql **m = (mysql **)lua_newuserdata(L, sizeof(mysql *));
    *m = new mysql;
    printf("对象地址为:%d\n", *m);
    luaL_getmetatable(L, "Weasel.mysql");
    lua_setmetatable(L, -2);
    return 1;
}

static int auto_gc(lua_State *L)
{
    printf("进入auto_gc \n");
    // mysql *m = *(mysql **)luaL_checkudata(L, 1, "Weasel.mysql");
    // printf("11111\n");
    // printf("对象地址为:%d\n", m);
    // if (m)
    // {
    //     printf("调用delete *m \n");

    //     delete m;
    // }

    void *p = luaL_testudata(L, 1, "Weasel.mysql");
    printf("p = %d \n", p);

    return 0;
}

static const struct luaL_Reg mysqllib_f[] = {
    {"create", newMysql},
    {NULL, NULL}};

static const struct luaL_Reg mysqllib_m[] = {
    {"__gc", auto_gc},
    {"close", auto_gc},
    {NULL, NULL}};

int luaopen_mysql(lua_State *L)
{
    luaL_newmetatable(L, "Weasel.mysql");
    lua_pushvalue(L, -1);
    lua_setfield(L, -2, "__index");
    luaL_setfuncs(L, mysqllib_m, 0);
    luaL_newlib(L, mysqllib_f);
    return 1;
}
